package com.yu.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yu.app.mapper.AddressMapper;
import com.yu.app.mapper.UserAddressMapper;
import com.yu.app.mapper.UserMapper;
import com.yu.app.pojo.Address;
import com.yu.app.pojo.UserAddress;
import com.yu.app.service.AddressService;
import com.yu.common.exception.ServiceException;
import com.yu.common.service.RedisService;
import com.yu.app.common.util.session.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
public class AddressServiceImpl implements AddressService {
    @Resource
    private AddressMapper addressMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserAddressMapper userAddressMapper;

    @Resource
    private RedisService redisService;

    @Override
    public Address getAddressDetail(Integer id) {
        return addressMapper.selectById(id);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addUserAddress(Address address) throws ServiceException {
        addressMapper.insert(address);
        UserAddress userAddress = new UserAddress();
        userAddress.setAddressId(address.getId());
        userAddress.setUserId(SessionUtil.getCurrentUserId());
        int userAddressCount = userAddressMapper.selectCount(
                new QueryWrapper<UserAddress>().eq("user_id", SessionUtil.getCurrentUserId())
        );
        if (userAddressCount >= 5)
            throw ServiceException.CONST_user_address_has_over_num;
        return userAddressMapper.insert(userAddress);
    }

    @Override
    public int updateUserAddress(Address address) {
        return addressMapper.updateById(address);
    }

}
